# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         script_runner.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2022/8/11 16:45
# -------------------------------------------------------------------------------
import logging

from apps.HttpAutoTestService.core.http_session_context import HttpSessionContext

logger = logging.getLogger(__name__)


class ScriptRunner(object):

    def __init__(self, http_session_context: HttpSessionContext = None):
        self.http_session_context = http_session_context
        self.result = None

    def run(self, code, param_names: tuple, *args):

        def sys_get(name):
            session_variable_keys = self.http_session_context.get_session_variable_keys()
            output_variable_keys = self.http_session_context.get_output_variable_keys()

            if name in output_variable_keys:
                return self.http_session_context.get_output_variable(name)
            elif name in session_variable_keys:
                return self.http_session_context.get_session_variable(name)
            else:
                return None

        def sys_put(name, value):
            self.http_session_context.update_output_variables({name: value})

        def sys_return(res):
            self.result = res

        temp_locals = locals()
        for index, value in enumerate(param_names):
            temp_locals[value] = args[index]

        exec(code, temp_locals)

        return self.result
